package com.global.college.ui.activity;


import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.global.college.BuildConfig;
import com.global.college.MainActivity;
import com.global.college.CollegeApplication;
import com.global.college.R;
import com.global.college.UserData;
import com.global.college.api.ProgressSubscriber;
import com.global.college.api.RequestClient;
import com.global.college.constants.PreKey;
import com.global.college.data.net.VersionBean;
import com.global.college.server.DownAPKService;
import com.global.college.utils.AppManagerUtils;
import com.global.college.utils.CommonUtils;
import com.global.college.utils.FileUtils;
import com.global.college.utils.PrefUtils;
import com.global.college.utils.RxTimer;
import com.global.college.utils.StringUtils;
import com.global.college.utils.ToastUtils;
import com.global.college.views.dialog.PermissionAndPrivacyDialogTip;
import com.global.college.views.dialog.UpdateDialog;
import com.gyf.barlibrary.ImmersionBar;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;

import java.io.File;
import java.util.List;

public class SplashActivity extends Activity implements DownAPKService.DownApk {//LogPermissionsActivity
    private static final String TAG = "SplashActivity";
    private AlertDialog dialog;
    PermissionAndPrivacyDialogTip commonDialogTip;

    private UpdateDialog appLoading = null;
    private String updateUrl = "";
    private RxTimer rxTimer;
    /**
     * 权限组
     */
    private static final String[] permissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        if (!CommonUtils.isPad(this)) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        }

        if (rxTimer == null) {
            rxTimer = new RxTimer();
        }
        showPermissionAndPrivacy();
        AppManagerUtils.getInstance().setSplashActivity(this);
        ImmersionBar.with(this)
                .statusBarColor(R.color.login_title)
                .statusBarDarkFont(true)
                .init();
    }

    /**
     * 展示权限及隐私提示
     */
    private void showPermissionAndPrivacy() {
        //如果用户是第一次使用
        boolean isFirstUse = PrefUtils.getBoolean(PreKey.SPLASH_FIRST_USE, true);
        if (isFirstUse) {
            //进入提示
            commonDialogTip = new PermissionAndPrivacyDialogTip(SplashActivity.this, new PermissionAndPrivacyDialogTip.OnCallBack() {
                @Override
                public void callBack(int param) {
                    if (1 == param) {
                        Log.i(TAG, "初次使用同意");
                        PrefUtils.setBoolean(PreKey.SPLASH_FIRST_USE, false);
                        //获取权限
                        getPermissions();
                    } else {
                        finish();
                    }
                }
            });
            commonDialogTip.show();
        } else {
            //跳过提示
            Log.i(TAG, "成功启动");
            getPermissions();
        }
    }



    /**
     * 进入首页
     */
    private void goToMainAct() {
        if (StringUtils.isEmpty(UserData.getInstance().getToken())) {
            Intent intent1 = new Intent();
            intent1.setClass(this, LoginByPswActivity.class);
            startActivity(intent1);
        } else {
            Intent intent2 = new Intent();
            intent2.setClass(this, MainActivity.class);
            startActivity(intent2);
        }
        finish();
    }

    public void getNewVersion() {
        RequestClient.getInstance().getVersionInfo().subscribe(new ProgressSubscriber<VersionBean>(this, false) {
            @Override
            public void onNext(VersionBean model) {
                if (!showAppVersionPop(model)) {
                    startTimer();
                }
            }
        });
    }

    private boolean showAppVersionPop(VersionBean appVersionModel) {
        if (StringUtils.isEmpty(appVersionModel.getDownloadURL())) {
            return false;
        }
        int newAppCode = Integer.valueOf(appVersionModel.getVersionNum());
        updateUrl = appVersionModel.getDownloadURL();
//        PrefUtils.setString(Constant.User.UPDATE_URL, updateUrl);
        if (BuildConfig.VERSION_CODE < newAppCode) {
            Log.i("SplashActivity", "has new version");
            if (appLoading == null) {
                appLoading = new UpdateDialog(SplashActivity.this);
                appLoading.builder();
                appLoading.setContent(appVersionModel.getContent());
                appLoading.setCancelable(false);
                //点击外部消失
                appLoading.setCanceledOnTouchOutside(false);
                appLoading.setConfirm("" + getString(R.string.update_immediately), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AndPermission.with(SplashActivity.this)
                                .requestCode(1000)
                                .permission(Permission.STORAGE)
                                .callback(permissionListener)
                                .start();
                    }
                }).show();
            } else {
                appLoading.setConfirm("" + getString(R.string.update_immediately), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AndPermission.with(SplashActivity.this)
                                .requestCode(1000)
                                .permission(Permission.STORAGE)
                                .callback(permissionListener)
                                .start();
                    }
                }).show();
            }
            return true;
        } else {
            Log.i("SplashActivity", "no new version");
            return false;

        }
    }

    private PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == 1000) {
                appLoading.download();
                Intent intent = new Intent(SplashActivity.this, DownAPKService.class);
                intent.putExtra("apk_url", updateUrl);
                startService(intent);
                DownAPKService.setDownApk(SplashActivity.this);
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
//            ToastUtils.showToastShort(R.string.please_access_perssion);
        }

    };

    /**
     * 进入登录或引导页
     */
    private void toNewLoginActivity() {
        //如果用户是第一次使用
        boolean isFirstUse = PrefUtils.getBoolean(PreKey.SPLASH_FIRST_USE, true);
        if (isFirstUse) {
            //引导界面
//            startActivity(new Intent(SplashActivity.this, GuideActivity.class));
        } else {
            //进入登录界面
//            startActivity(new Intent(SplashActivity.this, LoginActivity.class));
        }
        finish();
    }

    /**
     * 获取权限
     */
    private void getPermissions() {

        getNewVersion();

/*        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            int i = ContextCompat.checkSelfPermission(this, permissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (i != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                showDialogTipUserRequestPermission();
                PrefUtils.setBoolean(PreKey.Permission, false);
            } else {
                getNewVersion();
            }
        } else if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            getNewVersion();
        }*/
    }

    // 开始提交请求权限
    private void startRequestPermission() {
        ActivityCompat.requestPermissions(this, permissions, 321);
    }

    // 用户权限 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults.length > 0) {
                    if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                        // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    } else {
                        getNewVersion();

                    }
                }
            }
        }
    }

    // 提示用户去应用设置界面手动开启权限
    private void showDialogTipUserGoToAppSettting() {
        dialog = new AlertDialog.Builder(this)
                .setTitle(getString(R.string.permission_not_use))
                .setMessage(getString(R.string.permission_start_tip_info))
                .setPositiveButton(getString(R.string.permission_to_start), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                        //showDialogTipUserRequestPermission();
                    }
                })
                .setNegativeButton(getString(R.string.live_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ToastUtils.showCenterToast(R.string.please_access_perssion);
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, 123);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 检查该权限是否已经获取
                int i = ContextCompat.checkSelfPermission(this, permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 提示用户应该去应用设置界面手动开启权限
                    showDialogTipUserGoToAppSettting();
                } else {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    Toast.makeText(this, R.string.get_the_permission_success, Toast.LENGTH_SHORT).show();
                    getNewVersion();
                }
            }
        }
    }

    // 提示用户该请求权限的弹出框
    private void showDialogTipUserRequestPermission() {
//        new AlertDialog.Builder(this)
//                .setTitle("相机权限、读写权限")
//                .setMessage("由于需要摄像，需要开启相机权限\n" +
//                        "存储文件，需要开启读写权限\n" +
//                        "否则无法正常使用")
//                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
        startRequestPermission();
//                    }
//                })
//                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        ToastUtils.showCenterToast("请允许权限开启");
//                        finish();
//                    }
//                }).setCancelable(false).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (rxTimer != null) {
            rxTimer.cancel();
            rxTimer = null;
        }
        if (null != commonDialogTip && commonDialogTip.isShowing()) {
            commonDialogTip.dismiss();
        }
    }

    @Override
    public void onDownErrors() {
        downLoadFailed();
    }

    private void downLoadFailed() {
        Intent intent = new Intent(SplashActivity.this, DownAPKService.class);
        stopService(intent);
        appLoading.downloadFailure();
        appLoading.setConfirm("" + getString(R.string.update_immediately), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AndPermission.with(SplashActivity.this)
                        .requestCode(1000)
                        .permission(Permission.STORAGE)
                        .callback(permissionListener)
                        .start();
            }
        }).show();
    }

    @Override
    public void onDownloading(int progress) {
        downLoading(progress);
    }

    @Override
    public void onDownFinsh() {
        removeAppLoading();
        Intent intent = new Intent(SplashActivity.this, DownAPKService.class);
        stopService(intent);
        openFile(new File(Environment.getExternalStorageDirectory() + "/download/" + FileUtils.getNameFromUrl(updateUrl)), SplashActivity.this);
    }


    /**
     * 进度条实时更新
     *
     * @param i
     */
    public void downLoading(final int i) {
        SplashActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (appLoading == null) {
                    appLoading = new UpdateDialog(SplashActivity.this);
//                    appLoading.setMessage(getString(R.string.downloads) + "\n" + i + "%");
                    appLoading.setProgressBar(i);
                    appLoading.setCancelable(false);
                    appLoading.show();
                } else {
//                    appLoading.setMessage(getString(R.string.downloads) + "\n" + i + "%");
                    appLoading.setProgressBar(i);
                }
            }
        });
    }

    private void removeAppLoading() {
        if (appLoading != null) {
            appLoading.removeLoading();
            appLoading = null;
        }
    }

    //安装
    private void openFile(File file, Context context) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri apkUri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".fileProvider", file);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

    /**
     * 开始计时任务
     */
    private void startTimer() {
        if (rxTimer == null) {
            rxTimer = new RxTimer();
        }
        rxTimer.interval(1000, new RxTimer.RxAction() {
            @Override
            public void action(long number) {
                if (number == 3L) {
                    goToMainAct();
                }
            }
        });
    }
}